import axios from 'axios';
import jsCookie from 'js-cookie';
import { stringify } from 'qs';
import { BASE_URL, TIMEOUT } from "./config";


const service = axios.create({
	baseURL: BASE_URL,
	timeout: TIMEOUT
});

service.interceptors.request.use(config => {
	// 1.发送网络请求时, 在界面的中间位置显示Loading的组件
	// 2.某一些请求要求用户必须携带token, 如果没有携带, 那么直接跳转到登录页面

	// 3.params/data序列化的操作

	return config;
}, err => {

});

service.interceptors.response.use(res => {
	return res.data;
}, err => {
	if (err && err.response) {
		switch (err.response.status) {
			case 400:
				console.log("请求错误");
				break;
			case 401:
				console.log("未授权访问");
				break;
			default:
				console.log("其他错误信息");
		}
	}
	return err;
});

export default service;


export const fetchGet = (url, params = {}) => {

	return new Promise((resolve, reject) => {
		service({
			url,
			params: { cookie: encodeURIComponent(jsCookie.get('music-cookie')), ...params },
			method: 'GET',
		})
			.then((res) => {
				resolve(res)
			})
			.catch((error) => {
				reject(error)
			})
	})
}
/*
@name: fetchFormPost
@param {Type}
@returns {Type}
@description:用于formData数据的提交
@author: ChangHao
@time: 2021-09-08 10:56:41
*/
export const fetchFormGet = (url, data = {}) => {
	return new Promise((resolve, reject) => {
		service({
			url,
			data: stringify(data),
			method: 'GET',
		})
			.then((res) => {
				resolve(res)
			})
			.catch((error) => {
				reject(error)
			})
	})
}
/*
@name: fetchFormPost
@param {Type}
@returns {Type}
@description:用于formData数据的提交
@author: ChangHao
@time: 2021-09-08 10:56:41
*/
export const fetchFormPost = (url, data = {}) => {
	return new Promise((resolve, reject) => {
		service({
			url,
			data: stringify(data),
			method: 'POST',
		})
			.then((res) => {
				resolve(res)
			})
			.catch((error) => {
				reject(error)
			})
	})
}

export const fetchJsonPost = (url, data = {}) => {
	return new Promise((resolve, reject) => {
		service({
			url,
			data,
			method: 'POST',
		})
			.then((res) => {
				resolve(res)
			})
			.catch((error) => {
				reject(error)
			})
	})
}
export const fetchBlobPost = (url, data = {}) => {
	return new Promise((resolve, reject) => {
		service({
			url,
			data,
			responseType: 'blob',
			method: 'POST',
		})
			.then((res) => {
				resolve(res)
			})
			.catch((error) => {
				reject(error)
			})
	})
}
export const fetchBlobGet = (url, data = {}) => {
	return new Promise((resolve, reject) => {
		service({
			url,
			data,
			responseType: 'blob',
			method: 'GET',
		})
			.then((res) => {
				resolve(res)
			})
			.catch((error) => {
				reject(error)
			})
	})
}


